//
//  LanguageUIResultsViewController.swift
//  
//
//  Created by CSS on 8/17/23.
//

import UIKit
import MessageUI

class LanguageUIResultsViewController: UIViewController {
    
    @IBOutlet private weak var tableView: UITableView!
    @IBOutlet private weak var searchBar: LanguageSearchBar!

    var languageType: LanguageType = .chinese
    var languageNames: [String] = ["Localizable"]
    var customLanguageNames: [Bundle:String] = [:]
    
    private var languageSectionModels: [LanguageSectionModel] = []
    private var filterLanguageSectionModels: [LanguageSectionModel] = []
    private var selectLanguageModels: [LanguageModel] = []
    private var folderStatus: [Int:Bool] = [:]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = .init(image: .init(named: "nav_btn_email", in: .module, with: nil), style: .plain, target: self, action: #selector(emailButtonAction(_:)))
        navigationItem.rightBarButtonItem?.tintColor = .red
        
        tableViewSetup()
        searchBarSetup()
        reloadDatas()
    }

}

// MARK: UITableView处理类
extension LanguageUIResultsViewController: UITableViewDelegate, UITableViewDataSource {
    private func tableViewSetup() {
        tableView.register(.init(nibName: "LanguageResultCell", bundle: .module), forCellReuseIdentifier: "LanguageResultCell")
        tableView.rowHeight = UITableView.automaticDimension
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        filterLanguageSectionModels.sectionNums
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let folderStatus = folderStatus[section]
        if folderStatus == nil || folderStatus! {
            return filterLanguageSectionModels.rowNums(inSection: section)
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LanguageResultCell") as! LanguageResultCell
        let languageModel = filterLanguageSectionModels.languageModel(atIndexPath: indexPath)
        cell.model = languageModel
        cell.isModelSelect = selectLanguageModels.contains(where: { $0 == languageModel })
        cell.modelSelectChangeBlock = { [weak self] in
            guard let self, let model = $0 else {
                return
            }
            if let index = self.selectLanguageModels.firstIndex(where: { $0 == model }) {
                self.selectLanguageModels.remove(at: index)
            } else {
                self.selectLanguageModels.append(model)
            }
            self.tableView.reloadRows(at: [indexPath], with: .none)
        }
        cell.row = indexPath.row
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if filterLanguageSectionModels.sectionNums <= 1 {
            return 1
        }
        return 35
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if filterLanguageSectionModels.sectionNums <= 1 {
            let headerView = UIView()
            headerView.backgroundColor = .white
            return headerView
        }
        let headerView = LanguageResultHeaderView.defaultHeaderView()
        headerView.headerModel = filterLanguageSectionModels[section]
        headerView.folderStatusChangedBlock = { [weak self] in
            guard let self else {
                return
            }
            let folderStatus = self.folderStatus[section] ?? true
            self.folderStatus[section] = !folderStatus
            self.tableView.reloadData()
        }
        return headerView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let model = filterLanguageSectionModels.languageModel(atIndexPath: indexPath) else {
            return
        }
        let alertString = LanguageType.chinese.languageBundle.localizedString(forKey: model.key ?? "", value: model.key, table: filterLanguageSectionModels[indexPath.section].key)
        let alert = UIAlertController(title: "中文翻译", message: alertString, preferredStyle: .alert)
        let dismissAction = UIAlertAction(title: "确认", style: .default)
        alert.addAction(dismissAction)
        present(alert, animated: true)
    }
}

// MARK: UISearchBar处理类
extension LanguageUIResultsViewController: UISearchBarDelegate {
    private func searchBarSetup() {
        searchBar.delegate = self
        searchBar.tintColor = .systemBlue
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 280, right: 0)
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(false, animated: true)
        tableView.contentInset = .zero
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        reloadData(withFilterText: searchBar.text)
    }
    
    private func reloadData(withFilterText filterText: String? = nil) {
        guard let filterText, !filterText.isEmpty else {
            filterLanguageSectionModels = languageSectionModels
            tableView.reloadData()
            return
        }
        filterLanguageSectionModels = languageSectionModels.compactMap{ $0.filterModel(withSearchText: filterText) }
        tableView.reloadData()
    }
}

// MARK: 邮件处理类
extension LanguageUIResultsViewController: UINavigationControllerDelegate, MFMailComposeViewControllerDelegate {
    
    private func emailSelectModels() {
        if !MFMailComposeViewController.canSendMail() {
            let alert = UIAlertController(title: "友情提示", message: "没有登录邮箱", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "好的", style: .cancel) { _ in
                
            }
            alert.addAction(okAction)
            present(alert, animated: true) {
                
            }
            return
        }
        if selectLanguageModels.count == 0 {
            let alert = UIAlertController(title: "友情提示", message: "没有要到处的内容", preferredStyle: .alert)
            let dismissAction = UIAlertAction(title: "确认", style: .default)
            alert.addAction(dismissAction)
            present(alert, animated: true)
            return
        }
        let emailString = selectLanguageModels.reduce("", {
            if $0.isEmpty {
                return "\"\($1.key ?? "")\" = \"\($1.value ?? "")\";"
            }
            return $0 + "\n" + "\"\($1.key ?? "")\" = \"\($1.value ?? "")\";"
        })
        let mailComposeVC = MFMailComposeViewController()
        mailComposeVC.delegate = self
        mailComposeVC.mailComposeDelegate = self
        mailComposeVC.setSubject("翻译中有问题的部分")
        mailComposeVC.setToRecipients(["maboyq@163.com"])
        mailComposeVC.setMessageBody("\(languageType.languageName):\n" + emailString, isHTML: false)
        mailComposeVC.modalPresentationStyle = .fullScreen
        mailComposeVC.navigationBar.tintColor = .black
        if #available(iOS 13, *) {
            mailComposeVC.navigationBar.tintColor = .systemBlue
        }
        present(mailComposeVC, animated: true) {
            
        }
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true) { [weak self] in
            guard let self else {
                return
            }
            if result == .sent {
                self.selectLanguageModels.removeAll()
                self.tableView.reloadData()
            }
        }
    }
}

// MARK: 事件处理类
@objc private extension LanguageUIResultsViewController {
    func emailButtonAction(_ sender: Any) {
        emailSelectModels()
    }
}

// MARK: 数据处理类
private extension LanguageUIResultsViewController {
    func reloadDatas() {
        languageSectionModels.removeAll()
        guard languageNames.count > 0 || customLanguageNames.count > 0 else {
            tableView.reloadData()
            return
        }
        
        for languageName in languageNames {
            let stringBundle = languageType.languageBundle()
            if let stringPath = stringBundle.path(forResource: languageName, ofType: "strings") {
                if let tableStrings = NSDictionary(contentsOf: URL(fileURLWithPath: stringPath)) as? [String:String] {
                    let languageModels = tableStrings.reduce([LanguageModel](), {
                        $0 + [.init(key: $1.key, value: $1.value)]
                    }).sorted(by: { one, two in
                        (one.key ?? "") <= (two.key ?? "")
                    })
                    languageSectionModels.append(.init(key: languageName, languageModels: languageModels))
                }
            }
        }
        
        for (bundle, languageName) in customLanguageNames {
            let stringBundle = languageType.languageBundle(inBundle: bundle)
            if let stringPath = stringBundle.path(forResource: languageName, ofType: "strings") {
                if let tableStrings = NSDictionary(contentsOf: URL(fileURLWithPath: stringPath)) as? [String:String] {
                    let languageModels = tableStrings.reduce([LanguageModel](), {
                        $0 + [.init(key: $1.key, value: $1.value)]
                    }).sorted(by: { one, two in
                        (one.key ?? "") <= (two.key ?? "")
                    })
                    languageSectionModels.append(.init(key: languageName, languageModels: languageModels))
                }
            }
        }
        
        filterLanguageSectionModels = languageSectionModels
        tableView.reloadData()
        
        navigationItem.title = "\(languageType.languageName)(共\(languageSectionModels.totalLanguageModelNums)条记录)"
    }
    
}

class LanguageSearchBar: UISearchBar {
    
}
